package com.hmjk.health.health;

import java.util.ArrayList;
import java.util.Calendar;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.GlycoseData;
import com.hmjk.health.util.GlycoseReferenceSet;
import com.hmjk.health.util.GlycoseData.GLY_DETAIL;
import com.hmjk.health.views.GlucoseEdit;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class HealthGlucoseTarget extends Activity implements OnClickListener, OnFocusChangeListener{
	private final String TAG = HealthGlucoseTarget.class.getSimpleName();
	private HealthApp mApp = null;
	
	private String tid = "", subcode = "" ;
	
	private boolean admin = false;
	private TextView bDinnerRec = null;
	private TextView aDinnerRec = null;
	private TextView bSleepRec = null;
	private TextView bDawnRec = null;
	private GlucoseEdit bDinnerTargetFrom = null, bDinnerTargetTo = null;
	private GlucoseEdit aDinnerTargetFrom = null, aDinnerTargetTo = null;
	private GlucoseEdit bSleepTargetFrom = null, bSleepTargetTo = null;
	private GlucoseEdit bDawnTargetFrom = null, bDawnTargetTo = null;
	private TextView bDinnerOnTar = null, bDinnerHigh = null, bDinnerLow = null;
	private TextView aDinnerOnTar = null, aDinnerHigh = null, aDinnerLow = null;
	private TextView bSleepOnTar = null, bSleepHigh = null, bSleepLow = null;
	private TextView bDawnOnTar = null, bDawnHigh = null, bDawnLow = null;
	
	private final String GLUC_BEFORE_DINNER_REC_MMOL = "4.4 ~ 6.1 mmol/L";
	private final String GLUC_AFTER_DINNER_REC_MMOL = "4.4 ~ 8.0 mmol/L";
	private final String GLUC_BEFORE_SLEEP_REC_MMOL = "4.4 ~ 8.0 mmol/L";
	private final String GLUC_BEFORE_DAWN_REC_MMOL = "4.4 ~ 8.0 mmol/L";
	private final String GLUC_BEFORE_DINNER_REC_MG = "79 ~ 109 mg/dL";
	private final String GLUC_AFTER_DINNER_REC_MG = "79 ~ 144 mg/dL";
	private final String GLUC_BEFORE_SLEEP_REC_MG = "79 ~ 144 mg/dL";
	private final String GLUC_BEFORE_DAWN_REC_MG = "79 ~ 144 mg/dL";
	
	private final String GLUC_PERCENT_VALUE_INIT = "0%";
	
	private glucFenceCnt beforeFenceCnt = new glucFenceCnt(0, 0, 0);
	private glucFenceCnt afterFenceCnt = new glucFenceCnt(0, 0, 0);
	private glucFenceCnt bedFenceCnt = new glucFenceCnt(0, 0, 0);
	private glucFenceCnt dawnFenceCnt = new glucFenceCnt(0, 0, 0);
	
	private GlycoseReferenceSet setData;
	private boolean refreshing = false;
	
	private ArrayList<GLY_DETAIL> mDawnGlucList = new ArrayList<GlycoseData.GLY_DETAIL>();
	private ArrayList<GLY_DETAIL> mBeforeGlucList = new ArrayList<GlycoseData.GLY_DETAIL>();
	private ArrayList<GLY_DETAIL> mAfterGlucList = new ArrayList<GlycoseData.GLY_DETAIL>();
	private ArrayList<GLY_DETAIL> mBedGlucList = new ArrayList<GlycoseData.GLY_DETAIL>();
	
	private class glucFenceCnt{
		int good = 0;
		int high = 0;
		int low = 0;
		
		public glucFenceCnt(int goodCnt, int highCnt, int lowCnt){
			good = goodCnt;
			high = highCnt;
			low = lowCnt;
		}
		
		public void clear(){
			good = 0;
			high = 0;
			low = 0;
		}

	}
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
        super.onCreate(savedInstanceState);
    
        mApp = (HealthApp) getApplication();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.health_glucose_target);
        
        ImageButton butBack = (ImageButton)findViewById(R.id.back);
		butBack.setOnClickListener(this);
        
        Intent i = getIntent();
        tid = i.getStringExtra("tid");
        subcode = i.getStringExtra("subcode");
        logd("tid=" + tid + ", subcode=" + subcode);
        
        //recommendation
        bDinnerRec = (TextView)findViewById(R.id.before_dinner_rec);
        aDinnerRec = (TextView)findViewById(R.id.after_dinner_rec);
        bSleepRec = (TextView)findViewById(R.id.before_sleep_rec);
        bDawnRec = (TextView)findViewById(R.id.before_dawn_rec);
        
        //fence
        bDinnerOnTar = (TextView)findViewById(R.id.before_dinner_ontarget);
        bDinnerOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, GLUC_PERCENT_VALUE_INIT));
        bDinnerHigh = (TextView)findViewById(R.id.before_dinner_high);
        bDinnerHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, GLUC_PERCENT_VALUE_INIT));
        bDinnerLow = (TextView)findViewById(R.id.before_dinner_low);
        bDinnerLow.setText(getResources().getString(R.string.gluc_ctl_level_low, GLUC_PERCENT_VALUE_INIT));
        aDinnerOnTar = (TextView)findViewById(R.id.after_dinner_ontarget);
        aDinnerOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, GLUC_PERCENT_VALUE_INIT));
        aDinnerHigh = (TextView)findViewById(R.id.after_dinner_high);
        aDinnerHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, GLUC_PERCENT_VALUE_INIT));
        aDinnerLow = (TextView)findViewById(R.id.after_dinner_low);
        aDinnerLow.setText(getResources().getString(R.string.gluc_ctl_level_low, GLUC_PERCENT_VALUE_INIT));
        bSleepOnTar = (TextView)findViewById(R.id.before_sleep_ontarget);
        bSleepOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, GLUC_PERCENT_VALUE_INIT));
        bSleepHigh = (TextView)findViewById(R.id.before_sleep_high);
        bSleepHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, GLUC_PERCENT_VALUE_INIT));
        bSleepLow = (TextView)findViewById(R.id.before_sleep_low);
        bSleepLow.setText(getResources().getString(R.string.gluc_ctl_level_low, GLUC_PERCENT_VALUE_INIT));
        bDawnOnTar = (TextView)findViewById(R.id.before_dawn_ontarget);
        bDawnOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, GLUC_PERCENT_VALUE_INIT));
        bDawnHigh = (TextView)findViewById(R.id.before_dawn_high);
        bDawnHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, GLUC_PERCENT_VALUE_INIT));
        bDawnLow = (TextView)findViewById(R.id.before_dawn_low);
        bDawnLow.setText(getResources().getString(R.string.gluc_ctl_level_low, GLUC_PERCENT_VALUE_INIT));
        
        //editText
        bDinnerTargetFrom = (GlucoseEdit)findViewById(R.id.before_dinner_from);
        bDinnerTargetTo = (GlucoseEdit)findViewById(R.id.before_dinner_to);
        aDinnerTargetFrom = (GlucoseEdit)findViewById(R.id.after_dinner_from);
        aDinnerTargetTo = (GlucoseEdit)findViewById(R.id.after_dinner_to);
        bSleepTargetFrom = (GlucoseEdit)findViewById(R.id.before_sleep_from);
        bSleepTargetTo = (GlucoseEdit)findViewById(R.id.before_sleep_to);
        bDawnTargetFrom = (GlucoseEdit)findViewById(R.id.before_dawn_from);
        bDawnTargetTo = (GlucoseEdit)findViewById(R.id.before_dawn_to);
        /*
        bDinnerTargetFrom.setUserTag("bDinnerTargetFrom");
        bDinnerTargetTo.setUserTag("bDinnerTargetTo");
        aDinnerTargetFrom.setUserTag("aDinnerTargetFrom");
        aDinnerTargetTo.setUserTag("aDinnerTargetTo");
        bSleepTargetFrom.setUserTag("bSleepTargetFrom");
        bSleepTargetTo.setUserTag("bSleepTargetTo");
        bDawnTargetFrom.setUserTag("bDawnTargetFrom");
        bDawnTargetTo.setUserTag("bDawnTargetTo");
        */
        bDinnerTargetFrom.setOnFocusChangeListener(this);
        bDinnerTargetTo.setOnFocusChangeListener(this);
        aDinnerTargetFrom.setOnFocusChangeListener(this);
        aDinnerTargetTo.setOnFocusChangeListener(this);
        bSleepTargetFrom.setOnFocusChangeListener(this);
        bSleepTargetTo.setOnFocusChangeListener(this);
        bDawnTargetFrom.setOnFocusChangeListener(this);
        bDawnTargetTo.setOnFocusChangeListener(this);
        
        if(i.hasExtra("admin")){
        	admin = (i.getIntExtra("admin", 0) == 1);
        }
         
        if(!admin){
        	bDinnerTargetFrom.setEnabled(false);
        	bDinnerTargetTo.setEnabled(false);
        	aDinnerTargetFrom.setEnabled(false);
        	aDinnerTargetTo.setEnabled(false);
        	bSleepTargetFrom.setEnabled(false);
        	bSleepTargetTo.setEnabled(false);
        	bDawnTargetFrom.setEnabled(false);
        	bDawnTargetTo.setEnabled(false);
        }
		
		refreshing = mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_SET, new String[]{tid});
        if(refreshing){
        	mApp.showWaitting(this, null);
        }else{
        	queryGlucoseDetail();
			queryGlucoseData();
			updateView();
			
			caculateDawnFence();
			caculateBeforeFence();
			caculateAfterFence();
			caculateBedFence();
			updateFenceView();
        }
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(mReceiver);
		mApp.dismissWaiting();
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				if(t.equals(DataManager.F_GLYCOSE_SET)){
					if(refreshing){
						mApp.dismissWaiting();
						refreshing = false;
						queryGlucoseDetail();
						queryGlucoseData();
						updateView();
						
						caculateDawnFence();
						caculateBeforeFence();
						caculateAfterFence();
						caculateBedFence();
						updateFenceView();
					}
				}
			}else if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				mApp.dismissWaiting();
				String t = intent.getStringExtra("type");
				String state = intent.getStringExtra("state");
				if(t.equals(DataManager.F_GLYCOSE_SET)){
					if(state.equals("00")){
						mApp.showAlertDialog(HealthGlucoseTarget.this, getResources().getString(R.string.gluc_ctl_commit_ok), 
								R.string.ok, new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										HealthGlucoseTarget.this.setResult(RESULT_OK);
										finish();
									}
								});
						return;
					}
					logd("DATA_COMMIT_RESULT failed");
					mApp.showAlertDialog(HealthGlucoseTarget.this, getResources().getString(R.string.gluc_ctl_commit_err), null);
				}
				
			}
		}
		
	};
	
	private void updateView(){
		if(setData == null){
			return;
		}
		
		bDinnerTargetFrom.setMMOL(setData.beforelow);
		
		bDinnerTargetTo.setMMOL(setData.beforeupper);
		
		aDinnerTargetFrom.setMMOL(setData.afterlow);
		
		aDinnerTargetTo.setMMOL(setData.afterupper);
		
		bSleepTargetFrom.setMMOL(setData.bedtimelow);
		
		bSleepTargetTo.setMMOL(setData.bedtimeupper);
		
		bDawnTargetFrom.setMMOL(setData.dawnlow);
	
		bDawnTargetTo.setMMOL(setData.dawnupper);
	}
	
	private void setEditUintAndReference(){
		if(setData == null)
			return;
		
		if(bDinnerTargetFrom == null)
			return;
		
		bDinnerTargetFrom.setReference(setData.beforelow);
		bDinnerTargetFrom.setUnit(setData.unit);
		bDinnerTargetTo.setReference(setData.beforeupper);
		bDinnerTargetTo.setUnit(setData.unit);
		aDinnerTargetFrom.setReference(setData.afterlow);
		aDinnerTargetFrom.setUnit(setData.unit);
		aDinnerTargetTo.setReference(setData.afterupper);
		aDinnerTargetTo.setUnit(setData.unit);
		bSleepTargetFrom.setReference(setData.bedtimelow);
		bSleepTargetFrom.setUnit(setData.unit);
		bSleepTargetTo.setReference(setData.bedtimeupper);
		bSleepTargetTo.setUnit(setData.unit);
		bDawnTargetFrom.setReference(setData.dawnlow);
		bDawnTargetFrom.setUnit(setData.unit);
		bDawnTargetTo.setReference(setData.dawnupper);
		bDawnTargetTo.setUnit(setData.unit);
	}
	
	private void queryGlucoseDetail(){
		String[] args = {tid};
		setData = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, args);
		setEditUintAndReference();
		if(setData.unit == 0){
			bDinnerRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_BEFORE_DINNER_REC_MG));
	        aDinnerRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_AFTER_DINNER_REC_MG));
	        bSleepRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_BEFORE_SLEEP_REC_MG));
	        bDawnRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_BEFORE_DAWN_REC_MG));
		}else{
			bDinnerRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_BEFORE_DINNER_REC_MMOL));
	        aDinnerRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_AFTER_DINNER_REC_MMOL));
	        bSleepRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_BEFORE_SLEEP_REC_MMOL));
	        bDawnRec.setText(getResources().getString(R.string.gluc_ctl_recommendation, GLUC_BEFORE_DAWN_REC_MMOL));
		}
	}
	
	private void updateFenceView(){
		int high = 0;
		int low = 0;
		int good = 0;
		int total = beforeFenceCnt.good + beforeFenceCnt.high + beforeFenceCnt.low;
		if(total > 0){
			high = (100 * beforeFenceCnt.high) / (beforeFenceCnt.good + beforeFenceCnt.high + beforeFenceCnt.low);
			low = (100 * beforeFenceCnt.low) / (beforeFenceCnt.good + beforeFenceCnt.high + beforeFenceCnt.low);
			good = 100 - high - low;
		}
		bDinnerOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, String.valueOf(good) + "%"));
		bDinnerHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, String.valueOf(high) + "%"));
		bDinnerLow.setText(getResources().getString(R.string.gluc_ctl_level_low, String.valueOf(low) + "%"));
		
		high = 0;
		low = 0;
		good = 0;
		total = afterFenceCnt.good + afterFenceCnt.high + afterFenceCnt.low;
		if(total > 0){
			high = (100 * afterFenceCnt.high) / (afterFenceCnt.good + afterFenceCnt.high + afterFenceCnt.low);
			low = (100 * afterFenceCnt.low) / (afterFenceCnt.good + afterFenceCnt.high + afterFenceCnt.low);
			good = 100 - high - low;
		}
		aDinnerOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, String.valueOf(good) + "%"));
		aDinnerHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, String.valueOf(high) + "%"));
		aDinnerLow.setText(getResources().getString(R.string.gluc_ctl_level_low, String.valueOf(low) + "%"));
		
		high = 0;
		low = 0;
		good = 0;
		total = bedFenceCnt.good + bedFenceCnt.high + bedFenceCnt.low;
		if(total > 0){
			high = (100 * bedFenceCnt.high) / (bedFenceCnt.good + bedFenceCnt.high + bedFenceCnt.low);
			low = (100 * bedFenceCnt.low) / (bedFenceCnt.good + bedFenceCnt.high + bedFenceCnt.low);
			good = 100 - high - low;
		}
		bSleepOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, String.valueOf(good) + "%"));
		bSleepHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, String.valueOf(high) + "%"));
		bSleepLow.setText(getResources().getString(R.string.gluc_ctl_level_low, String.valueOf(low) + "%"));
		
		high = 0;
		low = 0;
		good = 0;
		total = dawnFenceCnt.good + dawnFenceCnt.high + dawnFenceCnt.low;
		if(total > 0){
			high = (100 * dawnFenceCnt.high) / (dawnFenceCnt.good + dawnFenceCnt.high + dawnFenceCnt.low);
			low = (100 * dawnFenceCnt.low) / (dawnFenceCnt.good + dawnFenceCnt.high + dawnFenceCnt.low);
			good = 100 - high - low;
		}
		bDawnOnTar.setText(getResources().getString(R.string.gluc_ctl_up_standard_week, String.valueOf(good) + "%"));
		bDawnHigh.setText(getResources().getString(R.string.gluc_ctl_level_high, String.valueOf(high) + "%"));
		bDawnLow.setText(getResources().getString(R.string.gluc_ctl_level_low, String.valueOf(low) + "%"));
	}
	
	private void verifyInput(GlucoseEdit fromedit, GlucoseEdit toedit, float low, float upper){
		float valueFrom = fromedit.getMMOL();
		float valueTo = toedit.getMMOL();
		boolean changedFrom = false;
		boolean changedTo = false;
		
		if(valueFrom > 33.0f){
			valueFrom = 33.0f;
			changedFrom = true;
		}else if(valueFrom < 1.0f){
			valueFrom = 1.0f;
			changedFrom = true;
		}
		
		if(valueTo > 33.0f){
			valueTo = 33.0f;
			changedTo = true;
		}else if(valueTo < 1.0f){
			valueTo = 1.0f;
			changedTo = true;
		}
		
		if(valueTo - valueFrom < 1.0f){
			valueFrom = low;
			valueTo = upper;
			changedTo = true;
			changedFrom = true;
		}
		
		if(changedFrom){
			fromedit.setMMOL(valueFrom);
		}
		
		if(changedTo){
			toedit.setMMOL(valueTo);
		}
		
	}
	
	private void caculateDawnFence(){
		float dawnupper = bDawnTargetTo.getMMOL();
		float dawnlow = bDawnTargetFrom.getMMOL();
		
		dawnFenceCnt.clear();
		for(GLY_DETAIL d:mDawnGlucList){
			if(d.bgvalue > dawnupper){
				dawnFenceCnt.high ++;
			}else if(d.bgvalue < dawnlow){
				dawnFenceCnt.low ++;
			}else {
				dawnFenceCnt.good ++;
			}
		}
	}
	
	private void caculateBeforeFence(){
		float beforeupper = bDinnerTargetTo.getMMOL();
		float beforelow = bDinnerTargetFrom.getMMOL();
		
		beforeFenceCnt.clear();
		for(GLY_DETAIL d:mBeforeGlucList){
			if(d.bgvalue > beforeupper){
				beforeFenceCnt.high ++;
			}else if(d.bgvalue < beforelow){
				beforeFenceCnt.low ++;
			}else {
				beforeFenceCnt.good ++;
			}
		}
	}
	
	private void caculateAfterFence(){
		float afterupper = aDinnerTargetTo.getMMOL();
		float afterlow = aDinnerTargetFrom.getMMOL();
		
		afterFenceCnt.clear();
		for(GLY_DETAIL d:mAfterGlucList){
			if(d.bgvalue > afterupper){
				afterFenceCnt.high ++;
			}else if(d.bgvalue < afterlow){
				afterFenceCnt.low ++;
			}else {
				afterFenceCnt.good ++;
			}
		}
	}
	
	private void caculateBedFence(){
		float bedtimeupper = bSleepTargetTo.getMMOL();
		float bedtimelow = bSleepTargetFrom.getMMOL();
		
		bedFenceCnt.clear();
		for(GLY_DETAIL d:mBedGlucList){
			if(d.bgvalue > bedtimeupper){
				bedFenceCnt.high ++;
			}else if(d.bgvalue < bedtimelow){
				bedFenceCnt.low ++;
			}else {
				bedFenceCnt.good ++;
			}
		}
	}
	
	private long getTimeInMillis(int year, int month, int day){
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month);
		c.set(Calendar.DATE, day);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		
		return c.getTimeInMillis();
	}
	
	private void queryGlucoseData(){	
		long MSEC_TIME_ONE_DAY = 24 * 60 * 60 * 1000;
		Calendar c = Calendar.getInstance();
		long timeNow = c.getTimeInMillis();
		long timeFrom = getTimeInMillis(c.get(Calendar.YEAR), c.get(Calendar.MONDAY), c.get(Calendar.DAY_OF_MONTH)) - 6 * MSEC_TIME_ONE_DAY;
		String[] argStrings = new String[]{tid, subcode, String.valueOf(timeFrom), String.valueOf(timeNow)};
		GlycoseData data = (GlycoseData) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_DATA, argStrings);
		if(data == null){
			return;
		}
		mDawnGlucList.clear();
		mBeforeGlucList.clear();
		mAfterGlucList.clear();
		mBedGlucList.clear();
		
		for(GLY_DETAIL d:data.getAddrList()){
			if(d.recordTime >= timeFrom){
				if(d.bgtype == 1){
					mDawnGlucList.add(d);
				}else if((d.bgtype == 2) || (d.bgtype == 4) || (d.bgtype == 6)){
					mBeforeGlucList.add(d);
				}else if((d.bgtype == 3) || (d.bgtype == 5) || (d.bgtype == 7)){
					mAfterGlucList.add(d);
				}else {
					mBedGlucList.add(d);
				}
			}
		}
	}
	
	private void commitAndFinish(){
		if(!admin){
			finish();
			return;
			
		}
		verifyInput(bDinnerTargetFrom,bDinnerTargetTo,setData.beforelow, setData.beforeupper);
		verifyInput(aDinnerTargetFrom,aDinnerTargetTo,setData.afterlow, setData.afterupper);
		verifyInput(bSleepTargetFrom,bSleepTargetTo,setData.bedtimelow, setData.bedtimeupper);
		verifyInput(bDawnTargetFrom,bDawnTargetTo,setData.dawnlow, setData.dawnupper);
		
		final GlycoseReferenceSet modify = new GlycoseReferenceSet(setData.tid);
		
		modify.beforelow = bDinnerTargetFrom.getMMOL();
		modify.beforeupper = bDinnerTargetTo.getMMOL();
		modify.afterlow = aDinnerTargetFrom.getMMOL();
		modify.afterupper = aDinnerTargetTo.getMMOL();
		modify.bedtimelow = bSleepTargetFrom.getMMOL();
		modify.bedtimeupper = bSleepTargetTo.getMMOL();
		modify.dawnlow = bDawnTargetFrom.getMMOL();
		modify.dawnupper = bDawnTargetTo.getMMOL();
		modify.unit = setData.unit;
		modify.voice = setData.voice;
		modify.glycosylated = setData.glycosylated;
		
		if(modify.compare(setData)){
			mApp.showConfirmDialog(this, getResources().getString(R.string.gluc_ctl_commit_hint), new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(v.getId() == R.id.alert_but1){
						//commitGlucoseDetail();
						mApp.getDataManager().commitData(DataManager.F_GLYCOSE_SET, modify);
						mApp.showWaitting(HealthGlucoseTarget.this, null);
					}else{
						finish();
					}
				}
			});
		}else{
			finish();
		}
		
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			commitAndFinish();
		}break;
		}
		
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {

		if(event.getAction() == KeyEvent.ACTION_UP){
			if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){
				commitAndFinish();
				return true;
			}
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		if(hasFocus == false){
			switch(v.getId()){
			case R.id.before_dinner_from:
			case R.id.before_dinner_to:{
				logd("before meal editor lose focus");
				verifyInput(bDinnerTargetFrom,bDinnerTargetTo,setData.beforelow, setData.beforeupper);
				caculateBeforeFence();
				updateFenceView();
			}break;
			
			case R.id.after_dinner_from:
			case R.id.after_dinner_to:{
				logd("after meal editor lose focus");
				verifyInput(aDinnerTargetFrom,aDinnerTargetTo,setData.afterlow, setData.afterupper);
				caculateAfterFence();
				updateFenceView();
			}break;
			
			case R.id.before_sleep_from:
			case R.id.before_sleep_to:{
				logd("before sleep editor lose focus");
				verifyInput(bSleepTargetFrom,bSleepTargetTo,setData.bedtimelow, setData.bedtimeupper);
				caculateBedFence();
				updateFenceView();
			}break;
			
			case R.id.before_dawn_from:
			case R.id.before_dawn_to:{
				logd("before dawn editor lose focus");
				verifyInput(bDawnTargetFrom,bDawnTargetTo,setData.dawnlow, setData.dawnupper);
				caculateDawnFence();
				updateFenceView();
			}break;
			
			}
		}
	}
	
}
